<?php
require_once( $_SESSION[ "service_dir" ]  .'/../Application/' .FunctionApp::getAppDirectory(  1  ).'/' .'/'. "DataGameInfo.php"  )  ;
require_once( $_SESSION[ "service_dir" ]  .'/../Application/' .FunctionApp::getAppDirectory(  1  ).'/' .'/'. "DataGameManager.php"  )  ;
require_once( $_SESSION[ "service_dir" ]  .'/../Application/' .FunctionApp::getAppDirectory(  1  ).'/' .'/'. "DataUserGames.php"  )  ;
require_once( $_SESSION[ "service_dir" ]  .'/../Application/' .FunctionApp::getAppDirectory(  1  ).'/' .'/'. "DataUserRequests.php"  )  ;
require_once( $_SESSION[ "service_dir" ]  .'/../Application/' .FunctionApp::getAppDirectory(  1  ).'/' .'/'. "DataLeaderBoard.php"  )  ;
require_once( $_SESSION[ "service_dir" ]  .'/../Application/' .FunctionApp::getAppDirectory(  1  ).'/' .'/'. "DataTable.php"  )  ;
require_once( $_SESSION[ "service_dir" ]  .'/../Application/' .FunctionApp::getAppDirectory(  1  ).'/' .'/'. "DataGamePlay.php"  )  ;
require_once( $_SESSION[ "service_dir" ]  .'/../Application/' .FunctionApp::getAppDirectory(  1  ).'/' .'/'. "DataUserTablePlay.php"    )   ;
require_once( $_SESSION[ "service_dir" ]  .'/../Application/' .FunctionApp::getAppDirectory(  1  ).'/' .'/'. "InfoTable.php"  )  ;
require_once( $_SESSION[ "service_dir" ]  .'/../Application/' .FunctionApp::getAppDirectory(  1  ).'/' .'/'. "FunctionGamePlay.php"  )  ;
require_once( $_SESSION[ "service_dir" ]  .'/../Application/' .FunctionApp::getAppDirectory(  1  ).'/' .'/'. "FunctionGameCenter.php"  )  ;
require_once( $_SESSION[ "service_dir" ]  .'/../Application/' .FunctionApp::getAppDirectory(  1  ).'/' .'/'. "DataStream.php"  )  ;
require_once( $_SESSION[ "service_dir" ]  .'/../Application/' .FunctionApp::getAppDirectory(  1  ).'/' .'/'. "PDebug.php"  )  ;
require_once( $_SESSION[ "service_dir" ]  .'/../Application/' .FunctionApp::getAppDirectory(  1  ).'/' .'/'. "DataGameTest.php"  )  ;
class svc_GameCenter{
	private $args = null;
	function __construct($arg){
		$this->args = $arg;
	}
	function getPublish(){
		$appid = DataGameManager::getAppID();
		$lang = $this->args["lang"];
		if($lang == null || $lang == "") $lang = "html";
		$request = $this->args["request"];
		$rs = new Result();
		$rs->addData("request",$request);
		if($lang == 'bin'){
			$rcode = $this->args['rcode'];
			if($rcode == null || $rcode == '')$rcode = 0;
			$rs->addData("rcode",0 + $rcode);
		}
		if($request == "getPage"){
			$tools = array(
				array('license_area'=> null ,'license_role'=> (3)  ,'type'=> 'button' ,'action'=> 'Context.dialog.request('.$appid.',"addGame");' ,'title'=> "New Game" ,'icon'=> 'images/' ."add_group.png" ) ,
				array('license_area'=> null ,'license_role'=> (3)  ,'type'=> 'button' ,'action'=> 'Context.dialog.request('.$appid.',"getAllGames",document.getElementById("gc_working_area"));' ,'title'=> "get All Games" ,'icon'=> 'images/' ."add_group.png" ) ,
				array('license_area'=> null ,'license_role'=> (3)  ,'type'=> 'button' ,'action'=> 'Context.dialog.request('.$appid.',"getPlayedGame",document.getElementById("gc_working_area"));' ,'title'=> "Played Game" ,'icon'=> 'images/' ."add_group.png" ) ,
				array('license_area'=> null ,'license_role'=> (3)  ,'type'=> 'button' ,'action'=> 'Context.dialog.request('.$appid.',"statistic",document.getElementById("gc_working_area"));' ,'title'=> "Statistic" ,'icon'=> 'images/' ."add_group.png" ) 
			);
			$ptn = readPattern($_SESSION[ "service_dir" ]  .'/../Application/' .FunctionApp::getAppDirectory(   $appid   ).'/' .'pattern/' . ('ptn_'.  "gamecenter"  ) .'.php' );
			$ptn_button = readPattern($_SESSION[ "service_dir" ]  .'/pattern/' .'ptn_'. 'item_button' .'.php' );
			$ptn->gamelist = '';
			$ptn->tools = '';
			if(Session::isLogin()){
				if(is_array($tools)){
					foreach($tools as $tool){
						if($tool['type'] == "button"){
							if($tool['license_area'] == null || (Session::getRoleOfArea( $tool['license_area'] ) >=  $tool['license_role'] ) ){
								$ptn_button->title = $tool['title'];
								$ptn_button->icon = $tool['icon'];
								$ptn_button->action = "";
								$ptn_button->action = $tool['action'];
								$tools_str.=  $ptn_button ->publish() ;
							}
						}
					}
					$ptn->tools = $tools_str;
				}
				$games_id = FunctionGameCenter::getGamesOfUser(Session::getID());
				if(is_array($games_id)){
					foreach($games_id as $gameid){
						$gameinfo = FunctionGameCenter::readGameInfo($gameid);
						if($gameinfo != null){
							$ptn->gamelist .= "<div>";
							$ptn->gamelist .= $gameinfo->getName();
							$ptn->gamelist .= $gameinfo->getInfomation();
							$ptn->gamelist .= "</div>";
						}
					}
				}
			}else{
				$ptn->gamelist = 'Please login to show your game.';
			}
			$rs->addData("content", $ptn ->publish() );
			$rs->return = true;
		}else if($request == "addGame"){
			$gamename = $this->args["game_name"];
			$description = $this->args["description"];
			$srs = FunctionGameCenter::registeAGame($gamename,$description);
			$rs->merge($srs);
			$rs->return = $srs->return;
		}else if($request == "loadGameInfo"){
			if(Session::isLogin()){
				$appid = DataGameManager::getAppID();
				{ $ptnmng  = new Util\str\PatternManager( $_SESSION[ "service_dir" ]  .'/../Application/' .FunctionApp::getAppDirectory(   $appid   ).'/' .'pattern/' . ('ptn_'.  "leaderboard"  ) .'.php'  );} ;
				$gameid = $this->args["game_id"];
				$game = FunctionGameCenter::readGameInfo($gameid);
				if($game != null){
					$ptn = $ptnmng->main;
					$ptn->boards = '';
					$ptn->appid = $appid;
					$ptn->gameid = $gameid;
					$ptn_board_section = $ptnmng->section;
					$ptn_board_item = $ptnmng->item;
					$boards = $game->getLeaderBoards();
					if(is_array($boards)){
						foreach($boards as $board){
							$boardid = $board->getID();
							$boardobj = FunctionGameCenter::readLeaderBoard($gameid, $boardid);
							$records = $boardobj->getLeaders();
							$ptn_board_section->title = $board->getTitle();
							$ptn_board_item->class = "title";
							$ptn_board_item->userid =	"UserID";
							$ptn_board_item->username = "User Name";
							$ptn_board_item->score = "Score";
							$ptn_board_section->items .=  $ptn_board_item ->publish() ;
							$ptn_board_item->class = "";
							if(is_array($records)){
								foreach($records as $record){
									$ptn_board_item->userid = $record->getUserID();
									$ptn_board_item->username = FunctionData::getIdentifyFromId($record->getUserID());
									$ptn_board_item->score = $record->getScore();
									$ptn_board_section->items .=  $ptn_board_item ->publish() ;
								}
							}
							$ptn->boards .=  $ptn_board_section ->publish() ;
						}
					}
					$rs->addData("content", $ptn ->publish() );
				}else{
				}
			}else{
				{Error::getInstance() ->addError( 17  , "Please login first!" );} ;
			}
		}else if($request == "loadGameTable"){
			if(Session::isLogin()){
				$gameid = $this->args["game_id"];
				$game = FunctionGameCenter::readGameInfo($gameid);
				if($game != null){
					$gameplay = FunctionGamePlay::readGamePlay($gameid);
					$numtable = $gameplay->NumTable;
					if($numtable > 0){
						{ $ptnmng  = new Util\str\PatternManager( $_SESSION[ "service_dir" ]  .'/../Application/' .FunctionApp::getAppDirectory(   $appid   ).'/' .'pattern/' . ('ptn_'.  "gametable"  ) .'.php'  );} ;
						$ptn = $ptnmng->main;
						$ptntable = $ptnmng->table;
						$ptnuser = $ptnmng->user;
						for($i = 0; $i < $numtable; $i++){
							$table = FunctionGamePlay::readGameTable($gameid, $i);
							$ptntable->userlist = '';
							$ptntable->status = $table->Status;
							$ptntable->transaction = $table->Transaction;
							for($j = 0; $j < $table->NumPlayer; $j++){
								$ptnuser->username = FunctionData::getDisplayNameOfId($table->Players[$j]["id"]);
								$ptntable->userlist .=  $ptnuser ->publish() ;
							}
							$ptn->tablelist .=  $ptntable ->publish() ; 
						}
						$rs->addData("content",  $ptn ->publish() );
					}
				}
			}else{
				{Error::getInstance() ->addError( 17  , "Please login first!" );} ;
			}
		}else if($request == "loadGame"){
			$appid = DataGameManager::getAppID();
			$gameid = $this->args["gid"];
			$game = FunctionGameCenter::readGameInfo($gameid);
			$boards = count($game->getLeaderBoards());
			$tournament_time = 180 ;
			$size = 4  + 4 ;
			$size += 2  + 2 ; 
			$buf = ByteBuffer::allocate( $size ) ;
			DataUtil::writeInt32( $buf ,  $tournament_time ) ;
			DataUtil::writeInt32( $buf ,  $boards ) ;
			DataUtil::writeInt16( $buf ,  0 ) ;
			DataUtil::writeInt16( $buf ,  0 ) ;
			$rs->return = true;
			$rs->addData("content", implode(array_map("chr",   $buf ->_array()  )) );
		}else if($request == "addLeaderBoard"){
			$gameid = $this->args["game_id"];
			$boardname = $this->args["name"];
			$boardlimit = 10;
			$subrs = FunctionGameCenter::createLeaderBoard($gameid,$boardname,$boardlimit);
			$rs->return = $subrs->return;
			$rs->merge($subrs);
		}else if($request == "putScore"){
			$score = $this->args["score"];
			$gameid = $this->args["gameid"];
			$ensure_key = $this->args["md5"];
			$rs->return = FunctionGameCenter::putHighScore($gameid, $score, $ensure_key);
		}else if($request == "putScoreOnBoard"){
			$score = $this->args["score"];
			$gameid = $this->args["gameid"];
			$boardid = $this->args["boardid"];
			$ensure_key = $this->args["md5"];
			FunctionGameCenter::putHighScoreOnBoard($gameid,$boardid, $score, $ensure_key);
		}else if($request == "getLeaderBoard"){
			$gameid = $this->args["gameid"];
			$boardid = $this->args["boardid"];
			$revision = 0+$this->args["revision"];
			$game = FunctionGameCenter::readGameInfo($gameid);
			if($game != null){
				$boardobj = FunctionGameCenter::readLeaderBoard($gameid, $boardid);
				if($boardobj != null){
					$brevision = $boardobj->getRevision();
					$isupdate = false;
					if($revision != $brevision){
						$isupdate = true;
					}
					if($isupdate){
						if($lang == "bin"){ 
							$leaders = $boardobj->getLeaders();
							$size = 0;
							$size += 1 ; 
							$size += 4 ; 
							$size += 4 ; 
							$infos = array();
							if(is_array($leaders)){
								foreach($leaders as $leader){
									$id = $leader->getUserID();
									$name = unpack('C*', FunctionData::getIdentifyFromId($id) ) ;
									$score = $leader->getScore();
									$size += 4 ; 
									$size += 1 ;
									if(is_array($name)){
										$size += count($name);
									}
									$size += 4 ;
									$infos[] = array('id'=>$id,'name'=>$name,'score'=>$score);
								}
							}
							$buf = ByteBuffer::allocate( $size ) ;
							DataUtil::writeInt8( $buf , $boardid ) ;
							DataUtil::writeInt32( $buf , $brevision ) ;
							DataUtil::writeInt32( $buf , count($leaders) ) ;
							if(is_array($infos)){
								foreach($infos as $info){
									DataUtil::writeInt32( $buf , $info['id'] ) ;
									DataUtil::writeBBin( $buf , $info['name'] ) ;
									DataUtil::writeInt32( $buf , $info['score'] ) ;
								}
							}
							$rs->return = true;
							$rs->addData("content",implode(array_map("chr",   $buf ->_array()  )) );
						}
					}else{
						$rs->addData("content","old revision:".$brevision);
					}
				}else{
					$rs->addData("content","cannot found board");
				}
			}else{
				$rs->addData("content","cannot read game");
			}
		}else if($request == "getFbToken"){
			if(Session::isLogin()){
				$gameid = $this->args["gid"];
				$gameinfo = FunctionGameCenter::readGameInfo($gameid);
				if($gameinfo != null){
					$fbappid = $gameinfo->getFbAppId();
					$fbtoken = FunctionData::getFBToken($fbappid,Session::getID());
					$fbid = FunctionData::getFbIdByUserId(Session::getID());
					$fbidbytes = unpack('C*', $fbid ) ;
					if($fbtoken != null){
						$rs->return = true;
						$bin = $fbtoken->getBinary();
						$size = 0;
						$size += count($bin);
						$size += 1  + count($fbidbytes);
						$buf = ByteBuffer::allocate( $size ) ;
						DataUtil::writeBytes( $buf ,  $bin ) ;
						DataUtil::writeBBin( $buf , $fbidbytes ) ;
						$rs->addData("content", implode(array_map("chr",   $buf ->_array()  )) );
					}else{
						echo "not have token";
					}
				}else{
					echo "game info not found";
				}
			}else{
				echo "not login";
			}
		}else if($request == "updateFbToken"){
			if(Session::isLogin()){
				$gameid = $this->args["gid"];
				$gameinfo = FunctionGameCenter::readGameInfo($gameid);
				if($gameinfo != null){
					$fbappid = $gameinfo->getFbAppId();
					$token = $this->args["token"];
					$ex = $this->args["exdate"];
					$fbtoken = new DataFbToken();
					$fbtoken->setToken($token, $ex);
					FunctionData::setFBToken($fbappid, Session::getID(), $fbtoken);
				}
			}
		}else if($request == "getFbFriendTournament"){
			if(Session::isLogin()){
				$gameid = $this->args["gid"];
				$md5 = $this->args["md5"];
				$ids_data = DataUtil::decodeUrl($this->args["ids"]);
				$buf = ByteBuffer::wrap( $ids_data ) ;
				$nof_id = DataUtil::readInt32( $buf ) ;
				$ids = array();
				for($i = 0; $i < $nof_id; $i++){
					$tmp = DataUtil::readInt32( $buf ) ;
					$ids[] = $tmp;
				}
				$tournament = FunctionGameCenter::getTournamentWithFriendsList($gameid, Session::getID(), $ids);
				if($tournament != null){
					$size = 0;
					$size += 4 ; 
					$size += 4 ; 
					$size += 4 ; 
					$size += 4 ; 
					$size += 1 ; 
					$size += 4 ; 
					if(is_array($tournament["list"])){
						foreach($tournament["list"] as $item){
							$size += 4 ;
							$size += 1  + count($item["name"]);
							$size += 4 ;
						}
					}
					$buf = ByteBuffer::allocate( $size ) ;
					DataUtil::writeInt32( $buf ,  $tournament["tourid"] ) ;
					DataUtil::writeInt32( $buf ,  $tournament["curtourid"] ) ;
					DataUtil::writeInt32( $buf ,  $tournament["time"] ) ;
					DataUtil::writeInt32( $buf ,  $tournament["curtime"] ) ;
					DataUtil::writeInt8( $buf , ($tournament["reward"])?1:0 ) ;
					DataUtil::writeInt32( $buf , count($tournament["list"]) ) ;
					if(is_array($tournament["list"])){
						foreach($tournament["list"] as $record){
							DataUtil::writeInt32( $buf ,  $record["id"] ) ;
							DataUtil::writeBBin( $buf ,  $record["name"] ) ;
							DataUtil::writeInt32( $buf ,  $record["score"] ) ;
						}
					}
					$bytes =  $buf ->_array() ;
					$md5 = md5(implode(array_map("chr",  $bytes )) );
					{if(!isset(FunctionGamePlay::$static ) || FunctionGamePlay::$static ==null){FunctionGamePlay::$static  = new Memcache;FunctionGamePlay::$static ->connect("127.0.0.1" , 11214 ) or die ("Could not connect");};} ;
					$md5key = "gc_md5fbtour" .$gameid."_".Session::getID();
					$dbmd5 = FunctionGamePlay::$static ->get( $md5key ) ;
					if($dbmd5 == null || $dbmd5 != $md5 || $md5 != $md5_rev){
						$rs->return = true;
						$md5bytes = unpack('C*', $md5 ) ;
						$newsize = 0;
						$newsize += 2  + count($md5bytes) + $size;
						$bufsend = ByteBuffer::allocate( $newsize ) ;
						DataUtil::writeSBin( $bufsend ,  $md5bytes ) ;
						DataUtil::writeBytes( $bufsend , $bytes ) ;
						$bytessend =  $bufsend ->_array() ;
						$rs->addData("content", implode(array_map("chr",  $bytessend )) );
						{if(FunctionGamePlay::$static ->get( $md5key )==null)FunctionGamePlay::$static ->set( $md5key , $md5 );else FunctionGamePlay::$static ->replace( $md5key , $md5 );} ;
					}else{
						{Error::getInstance() ->addError( 26  , "No need update" );} ;
					}
				}else {
					{Error::getInstance() ->addError( 25  , "Tournament null" );} ;
				}
			}
		}else if($request == "passFBTournament"){
			if(Session::isLogin()){
				$appid = DataGameManager::getAppID();
				$gameid = $this->args["gid"];
				$tour = $this->args["tid"];
				$key = "_tlastid_" .$gameid;
				$lasttour = FunctionApp::getUserKey($appid, Session::getID(), $key);
				if($lasttour == null || ($lasttour != null && $lasttour < $tour)){
					$rs->return = true;
					FunctionApp::setUserKey($appid, Session::getID(), $key, $tour);
				}
			}
		}else if($request == "test"){
			$buf = ByteBuffer::allocate( 1 +10 ) ;
			DataUtil::writeInt8( $buf , 10 ) ;
			for( $i = 0; $i< 10; $i++){
				DataUtil::writeInt8( $buf , $i ) ;
			}
			$rs->addData("content",implode(array_map("chr",   $buf ->_array()  )) );
		}else if($request == "getLeaderBoards"){
			$gameid = $this->args['gameid'];
			$gameinfo = FunctionGameCenter::readGameInfo($gameid);
			if($gameinfo != null){
				$leaderboards = $gameinfo->getLeaderBoards();
				$size = 0;
				$size += 1 ;
				if(is_array($leaderboards)){
					foreach($leaderboards as $boardinfo){
						$size += $boardinfo->getBinSize();
					}
				}
				$buf = ByteBuffer::allocate( $size ) ;
				DataUtil::writeInt8( $buf , count($leaderboards) ) ;
				if(is_array($leaderboards)){
					foreach($leaderboards as $boardinfo){
						DataUtil::writeBytes( $buf , $boardinfo->getBinary() ) ;
					}
				}
				$rs->addData("content",implode(array_map("chr",   $buf ->_array()  )) );
				$rs->return = true;
			}else{
				$rs->return = false;
			}
		}else if($request == "getRequests"){
			$gameid = $this->args["gameid"];
			$revision = 0 + $this->args["revision"];
			if(Session::isLogin()){
				$requests = FunctionGameCenter::readUserRequests(SESSION::getID());
				$revision_update = $requests->getRevision();
				$requests_list = FunctionGameCenter::getRequestsOfGame($gameid,$revision);
				if(is_array($requests_list)){
					if($lang == "bin"){
						$size = 0;
						$size += 4 ; 
						$size += 4 ; 
						$records = array();
						foreach($requests_list as $request){
							$size += $request->getBinSize();
							$sid = $request->SenderID;
							$sender_name = unpack('C*', FunctionData::getDisplayNameOfId($sid) ) ;
							$size += 1 ;
							$size += count($sender_name);
							$records[] = array("request"=>$request,"sender_name"=>$sender_name);
						}
						if(is_array($records)){
							$buf = ByteBuffer::allocate( $size ) ;
							DataUtil::writeInt32( $buf , $revision_update ) ;
							DataUtil::writeInt32( $buf , count($records) ) ;
							foreach($records as $record){
								DataUtil::writeBytes( $buf , $record["request"]->getBinary() ) ;
								DataUtil::writeBBin( $buf , $record["sender_name"] ) ;
							}
							$rs->return = true;
							$rs->addData("content",implode(array_map("chr",   $buf ->_array()  )) );
						}
					}
				}
			}else{
			}
		}else if($request == "sendRequest"){
			if(Session::isLogin()){
				$friendid = $this->args["fid"];
				$gameid = $this->args["gameid"];
				$type = $this->args["type"];
				$check_info = $this->args["md5"];
				$message = $this->args["msg"];
				$game = FunctionGameCenter::readGameInfo($gameid);
				if($game != null){
					$game_secretkey = $game->getSecretKey();
					$str = Session::getID().$friendid.$gameid.$type.$game_secretkey;
					$md5 = md5($str);
					if($md5 == $check_info){
						if(FunctionGameCenter::putRequestToFriend($friendid,$gameid,$type,$message)){
							$rs->return = true;
						}
					}else{
						echo "check md5 false:mustbe:".$md5."\nreceive:".$check_info."\n";
						echo "str:".$str."\n";
					}
				}else{
					echo "cannot found game:".$gameid."\n";
				}
			}
		}else if($request == "getTournament"){
			if(Session::isLogin()){
				$gameid = $this->args["gid"];
				$md5_rev = $this->args["md5"];
				$result = FunctionGameCenter::getTournamentOfUser($gameid, Session::getID());
				if($result != null || count($result) >= 1 ){
					if($lang == "bin"){
						$size = 0;
						$size += 4 ; 
						$size += 4 ; 
						$infos = array();
						if(is_array($result)){
							foreach($result as $friend){
								$name = unpack('C*', $friend['name'] ) ;
								$infos[] = array(
									'id'=>$friend['id'],
									'name'=>$name,
									'score'=>$friend['score']
								);
								$size += 4 ; 
								$size += 1  + count($name);
								$size += 4 ; 
							}
						}
						$tid = 0;
						$buf = ByteBuffer::allocate( $size ) ;
						DataUtil::writeInt32( $buf ,  $tid ) ;
						DataUtil::writeInt32( $buf ,  count($infos) ) ;
						if(is_array($infos)){
							foreach($infos as $info){
								DataUtil::writeInt32( $buf ,  $info['id'] ) ;
								DataUtil::writeBBin( $buf ,  $info['name'] ) ;
								DataUtil::writeInt32( $buf ,  $info['score'] ) ;
							}
						}
						$bytes =  $buf ->_array() ;
						$md5 = md5(implode(array_map("chr",  $bytes )) );
						{if(!isset(FunctionGamePlay::$static ) || FunctionGamePlay::$static ==null){FunctionGamePlay::$static  = new Memcache;FunctionGamePlay::$static ->connect("127.0.0.1" , 11214 ) or die ("Could not connect");};} ;
						$md5key = "gc_md5tour" .$gameid."_".Session::getID();
						$dbmd5 = FunctionGamePlay::$static ->get( $md5key ) ;
						if($dbmd5 == null || $dbmd5 != $md5 || $md5 != $md5_rev){
							$rs->return = true;
							$md5bytes = unpack('C*', $md5 ) ;
							$newsize = 4 ; 
							$newsize += 2  + count($md5bytes) + $size;
							$bufsend = ByteBuffer::allocate( $newsize ) ;
							DataUtil::writeInt32( $bufsend ,  (time()  % 180 ) ) ;
							DataUtil::writeSBin( $bufsend ,  $md5bytes ) ;
							DataUtil::writeBytes( $bufsend , $bytes ) ;
							$bytessend =  $bufsend ->_array() ;
							$rs->addData("content", implode(array_map("chr",  $bytessend )) );
							{if(FunctionGamePlay::$static ->get( $md5key )==null)FunctionGamePlay::$static ->set( $md5key , $md5 );else FunctionGamePlay::$static ->replace( $md5key , $md5 );} ;
						}else{
							$sendsize = 4 ; 
							$sendsize += 2 ;
							DataUtil::writeInt32( $bufsend ,  (time()  % 180 ) ) ;
							DataUtil::writeInt16( $bufsend ,  0 ) ;
						}						
					}
				}else{
				}
			}
		}else if($request == "getTournamentReward"){
			if(Session::isLogin()){
				$gameid = $this->args["gid"];
				$reward = FunctionGameCenter::getTournamentRewardOfUser($gameid,Session::getID());
				if($reward > 0){
					$rs->return = true;
					$size = 4 ;
					$buf = ByteBuffer::allocate( $size ) ;
					DataUtil::writeInt32( $buf ,  $reward ) ;
					$rs->addData("content",implode(array_map("chr",   $buf ->_array()  )) );
				}
			}
		}else if($request == "getGameData"){
			if(Session::isLogin()){
				$appid = DataGameManager::getAppID();
				$gameid = $this->args["gid"];
				$userid = Session::getID();
				$key = "_gdata_" .$gameid;
				$data = FunctionApp::getUserKey($appid, $userid, $key);
				if($data != null){
					$rs->return = true;
					$size = 4 ;
					$size += count($data);
					$buf = ByteBuffer::allocate( $size ) ;
					DataUtil::writeInt32( $buf ,  time()  ) ;
					DataUtil::writeBytes( $buf ,  $data ) ;
					$rs->addData("content",implode(array_map("chr",   $buf ->_array()  )) );
				}else{
				}
			}else{
				{Error::getInstance() ->addError( 17  , "Please login first!" );} ;
			}
		}else if($request == "saveGameData"){
			if(Session::isLogin()){
				$appid = DataGameManager::getAppID();
				$gameid = $this->args["gid"];
				$userid = Session::getID();
				$data = $this->args["data"];
				$key = "_gdata_" .$gameid;
				$decode_data = DataUtil::decodeData($data);
				for($i = 0; $i < count($decode_data); $i++){
					{Error::getInstance() ->addError( 0 , "i=".$i .' value:'.$decode_data[$i] );} ;
				}
				$size = 4  + 4  + count($decode_data);
				$buf = ByteBuffer::allocate( $size ) ;
				DataUtil::writeInt32( $buf ,  time()  ) ;
				DataUtil::writeInt32( $buf ,  count($decode_data) ) ;
				DataUtil::writeBytes( $buf ,  $decode_data ) ;
				FunctionApp::setUserKey($appid, $userid, $key,  $buf ->_array() );
				$rs->return = true;
			}else{
				{Error::getInstance() ->addError( 17  , "Please login first!" );} ;
			}
		}else if($request == "getTable"){
                    $game = $this->args['gid'];
                    if(Session::isLogin()){
                        $buf = ByteBuffer::allocate( 10 ) ;
                        for($i = 0 ; $i < 10 ; $i++){
                            DataUtil::writeInt8( $buf ,  $i ) ;
                        }
                        $rs->return = true;
                       $rs->addData("content", implode(array_map("chr",   $buf ->_array()  )) );
                    }
                }else if($request=="logoutTable"){
                    $gameid = $this->args["gid"];
			if(Session::isLogin()){
				$gameobj = FunctionGameCenter::readGameInfo($gameid);
                                $gameplay = FunctionGamePlay::readGamePlay($gameid);
				if($gameobj != null){
                                   $userdata = FunctionGamePlay::readUserDataTable($gameid, Session::getID());   
                                   if($userdata->Status == GC_USER_TABLE_DATA_STATUS_PLAYING){
                                       $table_obj = FunctionGamePlay::readGameTable($gameid,  $userdata->TableCurrentID);
                                       if($table_obj->NumPlayer > 0){  
                                           if($table_obj->Status == 2 ){
                                               $table_obj->Status--;
                                           }
                                           if($table_obj->NumPlayer == 0){
                                               $table_obj->reset();
                                           }else{                                                
                                                $table_obj->NumPlayer--;
                                           }
                                           $table_obj->removePlayer(Session::getID());                                           
                                           $gameplay->addTableWaitting($userdata->TableCurrentID);                                   
                                           FunctionGamePlay::writeGameTable($gameid, $userdata->TableCurrentID, $table_obj);                                   
                                           $userdata->free();                                   
                                           FunctionGamePlay::writeUserDataTable($gameid, Session::getID()  , $userdata->getBinary());   
                                           FunctionGamePlay::writeGamePlay($gameid, $gameplay);
                                       }
                                   }                                
                                }                                
                         }
                    $rs->return = true;
                }else if($request == 'receiveDataTable'){                
                }else if($request == 'setInfoTable'){                
                    if(Session::isLogin()){
			$gameid = $this->args["game_id"];
                        $maxplayer =$this->args["maxplayer"];
                        $minplayer =$this->args["minplayer"];
			$game = FunctionGameCenter::readGameInfo($gameid);
			if($game != null){
                            $infotable = new InfoTable($maxplayer, $minplayer);
                            FunctionGamePlay::writeInfoTable($gameid, $infotable->getBinary());
                            $rs->return = true;
                        }       
                   }                
                }else if($request == 'updateInfoTable'){                
                    if(Session::isLogin()){
			$gameid = $this->args["game_id"];
                        $maxplayer =$this->args["maxplayer"];
                        $minplayer =$this->args["minplayer"];
			$game = FunctionGameCenter::readGameInfo($gameid);
			if($game != null){
                            $infotable = new InfoTable($maxplayer, $minplayer);
                            FunctionGamePlay::writeInfoTable($gameid, $infotable->getBinary());
                            $rs->return = true;
                        }       
                   }
                }else if($request == 'UpdateStateLife'){                
                    if(Session::isLogin()){
			$gameid = $this->args["gid"]; 			
                        $userdata = FunctionGamePlay::readUserDataTable($gameid, Session::getID());                        
                        $table_obj = FunctionGamePlay::readGameTable($gameid, $userdata->TableCurrentID); 
                        $gameplay = FunctionGamePlay::readGamePlay($gameid);
                        $table_obj->Time = intval(time());    
                        $userdata->Time = intval(time());     
                        foreach ($table_obj->Players as $player){
                            if($userdata->UserID != $player['id']){
                                $user = FunctionGamePlay::readUserDataTable($gameid, $player['id']); 
                                if(($table_obj->Time - $user->Time) > GC_TIME_LIFE_PLAYER){
                                    if($table_obj->NumPlayer > 0){   
                                           if($table_obj->Status == 2 ){
                                               $table_obj->Status--;
                                           }
                                           if($table_obj->NumPlayer == 0){
                                               $table_obj->reset();
                                           }else{                                                
                                                $table_obj->NumPlayer--;
                                           }                                           
                                           $table_obj->removePlayer($player['id']);
                                           if($table_obj->NumPlayer < $table_obj->NumPlayerMin){
                                                $gameplay->addTableWaitting($userdata->TableCurrentID); 
                                           }                                                                             
                                           $user->free();                                   
                                           FunctionGamePlay::writeUserDataTable($gameid, $user->UserID  , $user->getBinary());   
                                    }
                                }
                            }                                    
                        } 
                        FunctionGamePlay::writeGamePlay($gameid, $gameplay);
                        FunctionGamePlay::writeGameTable($gameid, $userdata->TableCurrentID, $table_obj);                         
                        FunctionGamePlay::writeUserDataTable($gameid, Session::getID()  , $userdata->getBinary());   
                        $rs->return = true;
                        $rs->addData("content", implode(array_map("chr",  $table_obj->getBinary() )) );                        
                   }
                }else if($request == 'SendGameDataTable'){  
                    $gameid = $this->args["gid"]; 	
                    $data_game = $this->args["data"];
                    $seatid  = $this->args["seatid"];
                    if(Session::isLogin()){
                        $userdata = FunctionGamePlay::readUserDataTable($gameid, Session::getID());
                        FunctionGamePlay::writeDataGame(Session::getID(), CTBF($data_game));
                        $table_obj = FunctionGamePlay::readGameTable($gameid, $userdata->TableCurrentID);                        
                        if($seatid==GC_TRANSACTION_TO_ALL_USER){
                            $table_obj->sendDataToAll(CTBF($data_game));                          
                        }else{
                            $table_obj->sendDataToUser($seatid, CTBF($data_game));                            
                        }
                        FunctionGamePlay::writeGameTable($gameid, $userdata->TableCurrentID, $table_obj); 
                    }
                }else if($request == 'UpdateGameDataTable'){ 
                    $gameid = $this->args["gid"];
                    $tableid = $this->args["tid"];
                    $seatid  = $this->args["seatid"];
                    $seat_trans_id = (int)($this->args["seattrans_old"]);
                    if(Session::isLogin()){						
                        if($seat_trans_id > -1){                            
                             $seat_trans = FunctionGamePlay::readPlayerTransaction($gameid, $tableid, $seatid);
                             if(is_array($seat_trans)){
                                 if(count($seat_trans)>0){ 
                                    foreach($seat_trans as $k=>$s){
                                       if($s <= $seat_trans_id){
                                           unset($seat_trans[$k]);                  
                                       }
                                   }
                                   $seat_trans = array_values($seat_trans);
                                 }
                             }                             
                             FunctionGamePlay::writePlayerTransaction($gameid, $tableid, $seatid, $seat_trans);
							$table_obj = FunctionGamePlay::readGameTable($gameid, $tableid);
							$table_obj->removeTransactionData($seat_trans_id);
							FunctionGamePlay::writeGameTable($gameid, $tableid, $table_obj);
                        }							
                        $seat_trans = FunctionGamePlay::readPlayerTransaction($gameid, $tableid, $seatid);
                            if(is_array($seat_trans)){                                
                                if(count($seat_trans)>0){   
                                     $seat_trans = array_values($seat_trans);
                                     $data = FunctionGamePlay::readTransactionData($gameid, $tableid,$seat_trans[0]);
                                     $buf = ByteBuffer::allocate( 18 ) ;                                     
                                     DataUtil::writeInt32( $buf ,  $seat_trans[0] ) ;
                                     DataUtil::writeBytes($buf, $data);
                                     $rs->return = true;
                                     $rs->addData("content", implode(array_map("chr",   $buf ->_array()  ))  );
                                }
                            }
                    }
                }
                else if($request == 'DeleteSeatTrans'){
                    $gameid = $this->args["gid"];
                    $seat_trans_id = (int)($this->args["seattrans"]);
                    $tableid = $this->args["tid"];
                    $seatid  = $this->args["seatid"];
                    PLOG("Seat_transID : " . $seat_trans_id);
                    if(Session::isLogin()){
                        if($seat_trans_id >-1){                            
                             $seat_trans = FunctionGamePlay::readPlayerTransaction($gameid, $tableid, $seatid);
                             PLOG(json_encode($seat_trans));
                             if(is_array($seat_trans)){
                                 foreach($seat_trans as $k =>$s){
                                    if($s== $seat_trans_id){
                                        unset($seat_trans[$k]);
                                    }
                                }
                             }
                             FunctionGamePlay::writePlayerTransaction($gameid, $tableid, $seatid, $seat_trans);
                        }
                    }
                }
                else if($request == "findTable"){
			$gameid = $this->args["gid"];                        
			if(Session::isLogin()){                                
				$gameobj = FunctionGameCenter::readGameInfo($gameid);
				if($gameobj != null){
					$gameplay = FunctionGamePlay::readGamePlay($gameid);                                      
                                        if($gameplay->isTableWatting())
                                            $table = $gameplay->getAvailableTableWaitting();
                                        else
                                            $table = $gameplay->getAvailableTable();  
					$table_obj = FunctionGamePlay::readGameTable($gameid, $table);
                                        $userdata = FunctionGamePlay::readUserDataTable($gameid, Session::getID());                                       
                                        $infotable = FunctionGamePlay::readInfoTable($gameid);                                        
                                        $table_obj->NumPlayerMin = $infotable->MaxPlayer;
                                        $table_obj->NumPlayerMax = $infotable->MinPlayer;
                                        if(intval(time()) - $userdata->Time > GC_TIME_LIFE_PLAYER){
                                            $userdata->free();
                                        }
                                        if(!$userdata->isTable()){
                                            if($table_obj->Status == 0  ){                                                   
                                               $table_obj->Status = 1  ;
                                            }
                                            $seatid = $table_obj->addPlayer(Session::getID());
                                            if($seatid>=0){
                                                    if($table_obj->isFull()){
                                                            $table_obj->Status = 2  ;
                                                            if($gameplay->isTableWatting())
                                                                $gameplay->RemoveRableWatting($table);
                                                            else
                                                                $gameplay->removeAvailableTable($table);
                                                    }
                                            }
                                            $userdata->Status = GC_USER_TABLE_DATA_STATUS_PLAYING ;
                                            $userdata->GameID = $gameid;
                                            $userdata->TableCurrentID = $table;
                                            $userdata->UserID = Session::getID();
                                            $userdata->Time = intval(time());
                                            FunctionGamePlay::writeUserDataTable($gameid, Session::getID()  , $userdata->getBinary());
                                            $rs->return = true;
                                            FunctionGamePlay::writeGamePlay($gameid, $gameplay);
                                            FunctionGamePlay::writeGameTable($gameid, $table, $table_obj);
                                            $rs->addData("content", implode(array_map("chr",  $table_obj->getBinary() ))  );
                                        }
                                }
			}
		}else if($request == "getSeatIDTable"){
			$gameid = $this->args["gid"];
			$tableid = $this->args["tid"];			
			if(Session::isLogin()){
				$gameobj = FunctionGameCenter::readGameInfo($gameid);
				$table_obj = FunctionGamePlay::readGameTable($gameid, $tableid);
                                $seatid  = 0;
                                foreach($table_obj->Players as $k=>$p){
                                    if(Session::getID()==$p["id"]){
                                        $seatid = $k;
                                        break;
                                    }
                                }                               
                                $buf = ByteBuffer::allocate( 2  ) ;
                                DataUtil::writeInt16( $buf ,  $seatid ) ;
				$rs->return = true;
				$rs->addData("content", implode(array_map("chr",   $buf ->_array()  ))  );				
			}
		}else if($request == "updateTable"){
			$gameid = $this->args["gid"];
			$tableid = $this->args["tid"];
			$revision = $this->args["revision"];
			if(Session::isLogin()){
				$gameobj = FunctionGameCenter::readGameInfo($gameid);
				$table_obj = FunctionGamePlay::readGameTable($gameid, $tableid);
				if($table_obj->TableRevision != $revision){
					$rs->return = true;
					$rs->addData("content", implode(array_map("chr",  $table_obj->getBinaryOfTableInfo() )) );
				}
			}
		}else if($request == "cleanGameTable"){
			$gameid = $this->args["gid"];
			$gameobj = FunctionGameCenter::readGameInfo($gameid);
			if($gameobj != null){
				$gameplay = FunctionGamePlay::readGamePlay($gameid);
				$numtable = $gameplay->NumTable; 
					for($i = 0; $i <= $numtable; $i++){
						FunctionGamePlay::deleteGameTable($gameid, $i);
						$gameplay->removeAvailableTable($i);
					}
                                for($v = 0; $v < 7; $v++){
                                    FunctionGamePlay::deleteUserDataTable($gameid, $v);
                                    FunctionGamePlay::deleteDataGame($v);
				}
                                $table = FunctionGamePlay::readGameTable($gameid, 0);
                                for($k = 0 ; $k < 100 ; $k++){
                                    FunctionGamePlay::deleteTransactionData($gameid, 0, $k);
                                }
                                for($k = 0 ; $k < 4 ; $k++){
                                    FunctionGamePlay::deletePlayerTransaction($gameid, 0, $k);
                                }
				$gameplay->NumTable = 0;
				$gameplay->TableAvailable = array();
                                $gameplay->TableWaiting = array();
				FunctionGamePlay::writeGamePlay($gameid, $gameplay);
			}
		}else if($request == "testSendData"){
			$revdata = unpack('C*', $this->args["data"] ) ;
			if(count($revdata) > 0){
				$buf = ByteBuffer::wrap( $revdata ) ;
				$revision = DataUtil::readInt32( $buf ) ;
				$data = FunctionData::readKey("test");
				if($data != null){
					$rbuf = ByteBuffer::wrap( $data ) ;
					$rrevision = DataUtil::readInt32( $rbuf ) ;
					if($rrevision < $revision){
						FunctionData::writeKey("test",$revdata);
					}
				}else{
					FunctionData::writeKey("test",$revdata);
				}
				$rs->return = true;
			}
		}else if($request == "receiveData"){
			$data = FunctionData::readKey("test");
			if($data != null && is_array($data)){
				$rs->return = true;
				$size = 4 ; 
				$size += 4 ; 
				$size += 4 ; 
				$buf = ByteBuffer::allocate( $size ) ;
				DataUtil::writeInt32( $buf , 2* 4  ) ;
				DataUtil::writeBytes( $buf , $data ) ;
				$rs->addData("content", implode(array_map("chr",   $buf ->_array()  )) );
			}
		}else if($request == "getPlayedGame"){
			if(Session::isLogin()){
				$games_id = FunctionGameCenter::getGamesOfUser(Session::getID());
				if(is_array($games_id)){
					foreach($games_id as $gameid){
						$gameinfo = FunctionGameCenter::readGameInfo($gameid);
						if($gameinfo != null){
							$rs->addData($gameid,$gameinfo->getName());
							$rs->addData($gameid."_info",$gameinfo->getInfomation());
						}
					}
				}
			}else{
				{Error::getInstance() ->addError( 17  , "Please login." );} ;
			}
		}else if($request == "getRequest"){
			if(Session::isLogin()){
				$requests = FunctionGameCenter::getUserRequests(Session::getID())->getRequests();
				if(is_array($requests)){
				}
			}else{
				{Error::getInstance() ->addError( 17  , "Please login." );} ;
			}
		}else if($request == "getButtons"){
			{Error::getInstance() ->addError( 0 , "call getButtons of GameCenter" );} ;
			return array(
				array('license_area'=> "AreaRoot"  ,'license_role'=> (7)  ,'type'=> "button" ,'action'=> "service" ,'title'=> "GameCenter" ,'icon'=> "" ) 
			);
		}else{
			{Error::getInstance() ->addError( -1 , "Unknows Request" );} ;
		}
		return  $rs ->publish( $lang ) ;
	}
}
?>